package br.com.roteador.login;

import java.util.ResourceBundle;

import javax.inject.Inject;

import org.apache.commons.codec.binary.Base64;

import br.com.caelum.vraptor.Controller;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Result;
import br.com.roteador.component.AcessSession;
import br.com.roteador.component.PasswordEncryptionService;
import br.com.roteador.component.StringUteis;
import br.com.roteador.controller.BasicController;
import br.com.roteador.controller.HomeController;
import br.com.roteador.usuario.Usuario;
import br.com.roteador.usuario.UsuarioDAO;

@Controller
public class LoginController extends BasicController {
	@Inject private UsuarioDAO usuarioDAO;
	@Inject private AcessSession session;

	public LoginController(Result result, ResourceBundle bundle,
			UsuarioDAO usuarioDAO, AcessSession session) {
		this.result = result;
		this.bundle = bundle;
		this.usuarioDAO = usuarioDAO;
		this.session = session;
	}
	
	public LoginController(){}

	@Path(value = "/login/entrar")
	@Post
	public void entrar(Usuario usuario) {
		if(usuario != null){
			if(StringUteis.isEmpty(usuario.getEmail())){
    			mensagemErro("erro.email.usuario.obrigatorio");
    		}
    		if(StringUteis.isEmpty(usuario.getSenha())){
    			mensagemErro("erro.senha.usuario.obrigatorio");
    		}
    		if(resultPossui(ERROR) && resultPossuiConteudo(ERROR)){ redirect(); return;}
			Usuario temp = usuarioDAO.recuperaUsuariosPorEmail(usuario.getEmail());
			if(temp != null){
				PasswordEncryptionService pas = new PasswordEncryptionService();
				try {
					Boolean retorno = pas.authenticate(usuario.getSenha(), Base64.decodeBase64(temp.getSenha()), Base64.decodeBase64(temp.getChave()));
					if(retorno){
						session.setNome(temp.getNome());
						session.setUsuario(temp);
						result.redirectTo(HomeController.class).index();
					} else {
						mensagemErro("erro.usuario.nao.encontrado");
						result.redirectTo(HomeController.class).login();
					}
				} catch (Exception e) {
					mensagemErro("erro.usuario.nao.encontrado");
					result.redirectTo(HomeController.class).login();
				}
				
			} else {
				mensagemErro("erro.usuario.nao.encontrado");
				result.redirectTo(HomeController.class).login();
			}
		} else {
			mensagemErro("erro.ao.recuperar");
			result.redirectTo(HomeController.class).login();
		}
    }

	@Override
	protected void redirect() {}
	
}